package com.xbongbong.paas.controller;

import com.alibaba.fastjson.JSON;
import com.xbongbong.paas.elasticsearch.util.XbbElasticsearchRestTemplate;
import com.xbongbong.paas.pojo.dto.PrintLogDTO;
import com.xbongbong.paas.toolbox.exception.XbbException;
import com.xbongbong.paas.toolbox.wrap.XbbResponse;
import com.xbongbong.pro.config.ProBaseConfig;
import com.xbongbong.pro.constant.XbbProConstant;
import com.xbongbong.pro.enums.errorcodes.SystemErrorCodeEnum;
import org.springframework.http.MediaType;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.validation.Valid;
import java.util.Objects;

/**
 * 控制Elastic语句的输出
 * 加在各个项目里，注意url的前缀
 * @author 梁鲁江
 * @version v1.0
 * @date 2019/10/24 16:13
 * @since v1.0
 */
@RestController
@RequestMapping(value = XbbProConstant.API_ROOT_PREFIX + "/file/excel")
public class PrintElasticLogController {
    @Resource
    private ProBaseConfig proBaseConfig;
    @Resource
    private XbbElasticsearchRestTemplate xbbElasticsearchRestTemplate;
    @RequestMapping(value = "/setPrintLog", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public String setPrintLog(@RequestBody @Valid PrintLogDTO printLogDTO, BindingResult br) throws Exception {
        XbbResponse<String> response;
        if (br.hasErrors()) {
            String errMsg = Objects.requireNonNull(br.getFieldError()).getDefaultMessage();
            response = new XbbResponse<>(SystemErrorCodeEnum.API_ERROR_100002, errMsg);
        } else {
            try {
                if(!proBaseConfig.getXbbCode().equals(printLogDTO.getXbbCode())){
                    throw new XbbException(SystemErrorCodeEnum.API_ERROR_100006, SystemErrorCodeEnum.API_ERROR_100006.getMsg());
                }
                xbbElasticsearchRestTemplate.setPrintLog(printLogDTO.getPrintLog());
                response = new XbbResponse<>(printLogDTO.getPrintLog().toString());
            } catch (XbbException e) {
                response = new XbbResponse<>(e);
            }
        }
        return JSON.toJSONString(response);
    }
}
